package com.ellecity06.cwhiskymall.ui

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.PersistableBundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.ellecity06.common.base.BaseMvvmActivity
import com.ellecity06.common.helper.ClickHelper
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.common.utils.logD
import com.ellecity06.common.widgets.dialog.showAlert
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.adapter.LazyFragmentPagerAdapter
import com.ellecity06.cwhiskymall.databinding.ActivityMainBinding
import com.ellecity06.cwhiskymall.storage.UserStorage
import com.ellecity06.cwhiskymall.ui.calssify.ClassifyFragment
import com.ellecity06.cwhiskymall.ui.home.HomeFragment
import com.ellecity06.cwhiskymall.ui.live.LiveFragment
import com.ellecity06.cwhiskymall.ui.mine.MineFragment
import com.ellecity06.cwhiskymall.utils.NotificationUtils
import com.ellecity06.cwhiskymall.view.dialog.VersionUpdateDialog
import com.permissionx.guolindev.PermissionX


class MainActivity : BaseMvvmActivity<ActivityMainBinding, MainViewModel>(), View.OnClickListener {
    override val userBaseTitle: Boolean
        get() = false

    private val currentPosition: Int by lazy { intent.getIntExtra(PAGE_INDEX, 0) }
    private val fragments: MutableList<Fragment> = mutableListOf()
    private val homeFragment: HomeFragment by lazy { HomeFragment.newInstance() }
    private val classifyFragment: ClassifyFragment by lazy { ClassifyFragment.newInstance() }
    private val liveFragment: LiveFragment by lazy { LiveFragment.newInstance() }
    private val mineFragment: MineFragment by lazy { MineFragment.newInstance() }

    override fun inflateBinding(): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }

    //    private val titles = arrayOf("首页", "分类", "直播", "我的")
    override fun initialize(savedInstanceState: Bundle?) {
        logD("initialize=${UserStorage.user}")
        refreshBottomTab()
        fetchH5Host()
        checkHasNewVersion()
        initViewPager()
        handleBottomTab(currentPosition)
        // 检测通知状态
        checkNotification()


    }

    fun refreshBottomTab() {
        binding.cartView.visibility = UserStorage.upVisible()
    }

    /**
     * 检测是否开启通知,未开启的时候引导开启
     */
    private fun checkNotification() {

        if (NotificationUtils.areNotificationsEnabled()) return
        showAlert(content = "为避免错过优质内容，请允许开启手机通知") {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                if (ContextCompat.checkSelfPermission(
                        this,
                        Manifest.permission.POST_NOTIFICATIONS
                    ) !== PackageManager.PERMISSION_GRANTED
                ) {
                    PermissionX.init(this).permissions(Manifest.permission.POST_NOTIFICATIONS)
                        .request { allGranted, grantedList, deniedList ->
                            if (!allGranted) {
                                ToastUtils.show("您拒绝了授予接收通知权限！")
                            }
                        }
                } else {
                }
            } else {
                NotificationUtils.openNotificationSettingsForApp(this)
            }

        }
    }

    override fun initEvent() {
        binding.homeView.setOnClickListener(this)
        binding.mallView.setOnClickListener(this)
        binding.sendView.setOnClickListener(this)
        binding.cartView.setOnClickListener(this)
        binding.mineView.setOnClickListener(this)
    }

    override fun initObserver() {
        viewModel.state.observeEvent(this) {
            when (it) {
                is MainState.ShowDialog -> {
                    VersionUpdateDialog(this, it.data).show()
                }

                else -> {}
            }
        }
    }

    /**
     * 检查版本更新
     */
    private fun checkHasNewVersion() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(MainIntent.FetchLastVersion)
        }
    }

    /**
     * 检查版本更新
     */
    fun fetchH5Host() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(MainIntent.FetchH5Host)
        }
    }

    private fun initViewPager() {
        if (fragments.isEmpty()) {
            if (!homeFragment.isAdded) {
                fragments.add(homeFragment)
            }
            if (!classifyFragment.isAdded) {
                fragments.add(classifyFragment)
            }
            if (!liveFragment.isAdded) {
                fragments.add(liveFragment)
            }
            if (!mineFragment.isAdded) {
                fragments.add(mineFragment)
            }
        }
        binding.vpContent.adapter =
            LazyFragmentPagerAdapter(supportFragmentManager, fragments)
        binding.vpContent.offscreenPageLimit = fragments.size
        binding.vpContent.setCanScroll(false)


    }

    private fun handleBottomTab(index: Int) {
        when (index) {
            0 -> {
                binding.homeIcon.setImageResource(R.mipmap.icon_tab_home_selected)
                binding.mallIcon.setImageResource(R.mipmap.icon_tab_classify_default)
                binding.cartIcon.setImageResource(R.mipmap.icon_tab_cart_default)
                binding.cartIcon.setImageResource(R.mipmap.icon_tab_live_default)
                binding.mineIcon.setImageResource(R.mipmap.icon_tab_mine_default)
            }

            1 -> {
                binding.homeIcon.setImageResource(R.mipmap.icon_tab_home_default)
                binding.mallIcon.setImageResource(R.mipmap.icon_tab_classify_selected)
                binding.cartIcon.setImageResource(R.mipmap.icon_tab_cart_selected)
                binding.cartIcon.setImageResource(R.mipmap.icon_tab_live_default)
                binding.mineIcon.setImageResource(R.mipmap.icon_tab_mine_default)
            }

            2 -> {
                binding.homeIcon.setImageResource(R.mipmap.icon_tab_home_default)
                binding.mallIcon.setImageResource(R.mipmap.icon_tab_classify_default)
                binding.cartIcon.setImageResource(R.mipmap.icon_tab_cart_default)
                binding.cartIcon.setImageResource(R.mipmap.icon_tab_live_selected)
                binding.mineIcon.setImageResource(R.mipmap.icon_tab_mine_default)
            }

            3 -> {
                binding.homeIcon.setImageResource(R.mipmap.icon_tab_home_default)
                binding.mallIcon.setImageResource(R.mipmap.icon_tab_classify_default)
                binding.cartIcon.setImageResource(R.mipmap.icon_tab_cart_selected)
                binding.cartIcon.setImageResource(R.mipmap.icon_tab_live_default)
                binding.mineIcon.setImageResource(R.mipmap.icon_tab_mine_selected)
            }

            else -> {}
        }
        binding.homeTitle.isChecked = index == 0
        binding.mallTitle.isChecked = index == 1
        binding.cartTitle.isChecked = index == 2
        binding.mineTitle.isChecked = index == 3
        binding.vpContent.setCurrentItem(index, false)
        binding.vpContent.postDelayed({
            checkHasNewVersion()

        }, 500)
//        if (index==0&&homeFragment.isAdded&&homeFragment.isResumed){
//            homeFragment.showNewerDialog()
//        }
    }

    /**
     * 保存当前显示页面的索引
     */
    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
        super.onSaveInstanceState(outState, outPersistentState)
        outState.putInt("currentPosition", currentPosition)
        outState.remove("android:support:fragments")
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        val currentPosition = savedInstanceState.getInt("currentPosition", 0)
        binding.vpContent.setCurrentItem(currentPosition, false)
        handleBottomTab(currentPosition)
    }

    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.homeView -> {
                handleBottomTab(0)
            }

            R.id.mallView -> {
                handleBottomTab(1)
            }

            R.id.sendView -> {
//                handleBottomTab(2)
            }

            R.id.cartView -> {
                handleBottomTab(2)
            }

            R.id.mineView -> {
                handleBottomTab(3)
            }
        }
    }

    fun chooseClassify(id: Int) {
        handleBottomTab(1)
        classifyFragment.checkTop(id)
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        logD("onNewIntent=${UserStorage.isHasUp()}")
        binding.cartView.visibility = UserStorage.upVisible()
        if (intent != null) {
            val pageIndex = intent.getIntExtra(PAGE_INDEX, 0)
            handleBottomTab(pageIndex)
        }

    }

    override fun onBackPressed() {
        if (!ClickHelper.isOnDoubleClick()) {
            ToastUtils.show(getString(R.string.text_click_to_exit))
            return
        }
        super.onBackPressed()
    }

    companion object {
        private const val PAGE_INDEX = "key_page_index"
        fun launch(context: Context, index: Int = 0) {
            context.startActivity(
                Intent(context, MainActivity::class.java).putExtra(
                    PAGE_INDEX,
                    index
                )
            )
        }
    }

}